package com.omn.listazakupow.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;

import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.omn.listazakupow.db.model.ListaZakupow;
import com.omn.listazakupow.db.model.PozycjeListyZakupow;
import com.omn.listazakupow.db.service.ListaZakupowLocalServiceUtil;
import com.omn.listazakupow.db.service.PozycjeListyZakupowLocalServiceUtil;

@Controller
@RequestMapping("VIEW")
public class DefaultController {

	@RequestMapping("view")
	public void handleActionRequest(ActionRequest request,
			ActionResponse response) throws Exception {
	}

	@RequestMapping("view")
	public ModelAndView handleRenderRequest(RenderRequest request,
			RenderResponse response) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();

		/* Read params */
		String tab=request.getParameter("tabs1");
		String listaZakupowId=request.getParameter("listaZakupowId");
		String order=request.getParameter("order");
		
		if ( tab==null ) tab="";
		if ( listaZakupowId==null ) listaZakupowId="";
		if ( order==null ) order="kolejnosc";
		
		model.put("formTab", tab );

		/* Load Lists */
		DynamicQuery dq = DynamicQueryFactoryUtil.forClass(ListaZakupow.class);
		dq.addOrder( PropertyFactoryUtil.forName( "id" ).desc() );

		List<ListaZakupow> ls = ListaZakupowLocalServiceUtil.dynamicQuery(dq);
		String names = "";
		for (int i = 0; i < ls.size(); i++) {
			ListaZakupow zakup = ls.get(i);
			if ( (""+zakup.getId()).equals( listaZakupowId ) || zakup.getDescription().equals( tab ) ) {
				model.put("formTab", zakup.getDescription() );
				model.put("listaZakupowId", zakup.getId() );
				}				
			if (i != 0)
				names += ",";
			names += zakup.getDescription();
		}
		model.put("formNames", names);
		
		/* Load Items */
		DynamicQuery dqi=DynamicQueryFactoryUtil.forClass( PozycjeListyZakupow.class );
		dqi.add( PropertyFactoryUtil.forName( "listaZakupowId" ).eq(model.get("listaZakupowId")) );
		dqi.addOrder( PropertyFactoryUtil.forName( order ).asc() );

		List<PozycjeListyZakupow> is=PozycjeListyZakupowLocalServiceUtil.dynamicQuery( dqi );
		model.put("itemList", is);
		
		return new ModelAndView("view", model);
	}

	@RequestMapping
	protected String defaultView() {
		return "view";
	}

}
